﻿using System;

using Game.Controller;
using Game.Level;
using Game.Map.Extensions;

namespace Game.Surface
{
    public class AppSurfaceControl : SurfaceControl
    {
        public event EventHandler NextLevel;

        readonly GameController _GameController;

        public AppSurfaceControl(
            GameLevels levels,
            GameLevel level, 
            GameController controller)
            : base(level.GameMap)
        {
            _GameController = controller;

            _GameController.Events.GameStart += delegate
            {
                var gameEvent = level.Milestones[GameMilestoneType.Start];
                var dialog = new CommunicationDlg(gameEvent);
                dialog.Show();
            };

            _GameController.GameLevels.Events.GameFailure += delegate
            {
                var gameEvent = level.Milestones[GameMilestoneType.Failure];
                var dialog = new CommunicationDlg(gameEvent);
                dialog.Closed += (source2, args2) => levels.Events.FireGameEnded();
                dialog.ShowDialog();
            };

            _GameController.GameLevels.Events.GameSuccess += delegate
            {
                var gameEvent = level.Milestones[GameMilestoneType.Success];
                var dialog = new CommunicationDlg(gameEvent);
                dialog.ShowDialog();

                dialog.Closed += delegate
                {
                    if (NextLevel != null)
                    {
                        NextLevel(this, new EventArgs());
                    }
                };
            };

            _GameController.Events.FieldAttacked += delegate(object source, MapFieldEventArgs args)
            {
                var field = Fields[args.MapField.Point];
                new ExplosionDecorator(field);
            };

            GameMapView.MoveX().Move += OnMove;
        }

        public GameController GameController
        {
            get { return _GameController; }
        }

        public override void Start()
        {
            _GameController.Start();
        }

        void OnMove(object sender, MoveEventArgs e) 
        {
            var anamation = new MovePathAnamation(
                this, GameCanvas, e, e.GameTurn);
            anamation.Start();
            e.IsHandled = true;
        }
        
    }
    
}